const { Application } = require('ee-core');
const { app, ipcMain, globalShortcut } = require('electron');
const SerialPort = require('serialport');

class Index extends Application {

  constructor() {
    super();
    // this === eeApp;
  }

  /**
   * core app have been loaded
   */
  async ready() {
    // do some things
  }

  /**
   * electron app ready
   */
  async electronAppReady() {
    // do some things
  }

  /**
   * main window have been loaded
   */
  async windowReady() {
    // do some things
    // 延迟加载，无白屏
    const winOpt = this.config.windowsOption;
    let portList = [];

    if (winOpt.show == false) {
      const mainWindow = this.electron.mainWindow;

      mainWindow.once('ready-to-show', () => {
        mainWindow.show();
        mainWindow.focus();
      });

      globalShortcut.register('CommandOrControl+i', () => {
        mainWindow.webContents.toggleDevTools();
      });

      ipcMain.on('quit-app-request', () => {
        app.quit();
      });

      ipcMain.on('serial-port-close', () => {
        portList.forEach((port) => {
          if (port.isOpen) {
            port.close();
          }
        });

        portList = portList.filter((item) => !!item.isOpen);
      });

      ipcMain.on('serial-port-list', () => {
        SerialPort.SerialPort.list().then((ports) => {
          ports.forEach((item) => {
            const port = new SerialPort.SerialPort({
              path: item.path,
              baudRate: 9600,
            });

            portList.push(port);

            port.on('open', () => {
              port.on('data', (data) => {
                if (data.indexOf('catch') !== -1) {
                  mainWindow.webContents.send('serial-port-data-catch', item.path);
                } else {
                  port.close();
                }
              });
            });
          });
        });
      });
    }
  }

  /**
   * before app close
   */
  async beforeClose() {
    // do some things

  }
}

Index.toString = () => '[class Index]';
module.exports = Index;